package com.solairen.myapplication.utils

import android.content.Context
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.solairen.myapplication.Pager.KEY_LOGIN_STATUS
import com.solairen.myapplication.Pager.KEY_NAME
import com.solairen.myapplication.Pager.KEY_PWD
import com.solairen.myapplication.Pager.PREFS_NAME

/**
 *
 * @Date 2024/3/5 19:10
 */
private val gson = Gson()

fun Any.toJsonString(): String {
    return gson.toJson(this)
}

fun <T> String?.toModel(cls: Class<T>): T? {
    this?.let {
        try {
            return gson.fromJson(it, cls)
        } catch (e: Exception) {
            Log.d("fromJson", e.message ?: "")
        }
    }
    return null
}

fun <T> String.toList(cls: Class<T>): List<T> {
    val gson = Gson()
    val list: MutableList<T> = ArrayList()
    val array = JsonParser().parse(this).asJsonArray
    for (elem in array) {
        list.add(gson.fromJson(elem, cls))
    }
    return list
}

/**
 * 登入
 */
fun Context.login(username: String, password: String) {
    val sp = getSharedPreferences(PREFS_NAME, AppCompatActivity.MODE_PRIVATE)
    sp.edit().also {
        it.putString(KEY_NAME, username)
        it.putString(KEY_PWD, password)
        it.putBoolean(KEY_LOGIN_STATUS, true)
        it.apply()
    }
}

/**
 * 登出
 */
fun Context.logout() {
    val sp = getSharedPreferences(PREFS_NAME, AppCompatActivity.MODE_PRIVATE)
    sp.edit().also {
        it.putString(KEY_NAME, null)
        it.putString(KEY_PWD, null)
        it.putBoolean(KEY_LOGIN_STATUS, false)
        it.apply()
    }
}

fun visible(view: View) {
    view.visibility = View.VISIBLE
}

fun gone(view: View) {
    view.visibility = View.GONE
}